﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using DevExpress.XtraGrid;
using DevExpress.Utils;
using Lamex.Interface;
using Lamex.Base;
using System.Diagnostics;

namespace Lamex.mCapacity.UI
{
    public partial class frmCAP_Plan_Evaluation : frmBaseChild
    {
        DataTable OP_Capacity_Evaluation_Temp = null;
        public frmCAP_Plan_Evaluation()
        {
            InitializeComponent();
        }

        private void frmCAP_Plan_Evaluation_Resize(object sender, EventArgs e)
        {
            //防止主窗体最小化时报错
            try
            {
                splitContainer1.SplitterDistance = this.Width * 3 / 16;
                splitContainer2.SplitterDistance = this.Width * 7 / 16;
                splitContainer3.SplitterDistance = this.Width * 3 / 16;

                splitContainer4.SplitterDistance = 210;
            }
            catch (Exception ex)
            {
            }
        }

        private void frmCAP_Plan_Evaluation_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            OP_Capacity_Evaluation_Temp = new DataTable();
            OP_Capacity_Evaluation_Temp.TableName = "OP_Capacity_Evaluation_Temp";
            OP_Capacity_Evaluation_Temp.Columns.Add("MO_NO");
            OP_Capacity_Evaluation_Temp.Columns.Add("MATERIAL_NO");
            OP_Capacity_Evaluation_Temp.Columns.Add("QTY",typeof(decimal));

            //textBox1.Text = "645367006809" + "\r\n" + "645367013209";

        }

        private void sbtnView_Click(object sender, EventArgs e)
        {
            using (WaitDialogForm wdf = new WaitDialogForm("请稍侯", "数据分析中......", new Size(400, 80)))
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();

                gridControl1.DataSource = null;
                gridControl2.DataSource = null;
                gridControl3.DataSource = null;
                gridControl4.DataSource = null;
                gridControl5.DataSource = null;

                gridView1.Columns.Clear();
                gridView2.Columns.Clear();
                gridView3.Columns.Clear();
                gridView4.Columns.Clear();
                gridView5.Columns.Clear();

                //将分析数据插入到临时表
                insertTempDataToTable();

                if (textBox1.Text.Substring(0, 1) == "6" || textBox1.Text.Substring(0, 1) == "1") //(radioGroup1.SelectedIndex==0)
                {
                    refreshDataToFront_Order();
                }
                else
                {
                    refreshDataToFront_Product();
                }

                TotalSum_FirstColumn();
                TotalSum_OtherColumn();

                sw.Stop();
                TimeSpan tt = sw.Elapsed;
                DevExpress.XtraEditors.XtraMessageBox.Show("数据刷新成功，共用时 " + Math.Round(tt.TotalSeconds, 1) + " 秒！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        //将分析数据插入到临时表
        private void insertTempDataToTable()
        {
            string strContent = "";
            string tableName = OP_Capacity_Evaluation_Temp.TableName;
            string sql = "insert into " + tableName + "( ";
            string sql2 = "select ";
            string field = "";
            string field2 = "";
            DataSet ds = new DataSet();
            ds.Clear();
            OP_Capacity_Evaluation_Temp.Rows.Clear();
            BaseBuildSql.ExecuteNonQuery(" delete from OP_Capacity_Evaluation_Temp");
            //split String to be columns
            if (!string.IsNullOrEmpty(textBox1.Text))
            {
                if (textBox1.Text.ToString().Contains("\r\n") && textBox1.Text.ToString().Contains("\t"))
                {
                    string[] strArray = textBox1.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                    if (strArray.Count() != 0)
                    {
                        foreach (string s in strArray)
                        {
                            if (!string.IsNullOrEmpty(s))
                            {
                                string[] splitColArray = s.Split(new string[] { "\t" }, StringSplitOptions.None);
                                if (splitColArray.Count() > 0)
                                {
                                    DataRow dr = OP_Capacity_Evaluation_Temp.NewRow();
                                    dr["MO_NO"] = null;
                                    dr["MATERIAL_NO"] = splitColArray[0];
                                    if (string.IsNullOrEmpty(splitColArray[1]))
                                        dr["QTY"] = 0;
                                    else
                                        dr["QTY"] = splitColArray[1];
                                    OP_Capacity_Evaluation_Temp.Rows.Add(dr);
                                }
                            }
                        }

                    }

                }
                else
                {
                    string[] strArray = textBox1.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                    if (strArray.Count() != 0)
                    {
                        foreach (string s in strArray)
                        {
                            if (!string.IsNullOrEmpty(s))
                            {
                                DataRow dr = OP_Capacity_Evaluation_Temp.NewRow();
                                dr["MO_NO"] = s;
                                dr["MATERIAL_NO"] = null;
                                dr["QTY"] = 0;
                                OP_Capacity_Evaluation_Temp.Rows.Add(dr);
                            }
                        }
                    }

                }
            }
            //insert  DataList into temp datatable OP_Capacity_Evaluation_Temp
            foreach (DataColumn d in OP_Capacity_Evaluation_Temp.Columns)
            {
                field += d.ColumnName + ",";
                field2 += d.ColumnName + ",";
            }
            field = field.Trim(',');
            field2 = field2.Trim(',');
            sql += field;
            sql2 += field2;

            sql += " ) ";
            sql2 += " from #" + tableName + "";
            sql = sql + sql2;
            DataTable dtImport = new DataTable();
            dtImport = OP_Capacity_Evaluation_Temp.Copy();
            ds.Tables.Add(dtImport);
            string errMsg = "";
            if (!BaseBuildSql.ExecuteInsertBulkData("select  " + field + "  into #" + tableName + " from  " + tableName + " where 1!=1", ds, sql, ref errMsg))
            {
                XtraMessageBox.Show(errMsg);
                return;
            }
        }

        //按产品预估
        private void refreshDataToFront_Product()
        {

//4033245616	2
//4960286341	3
//4311200010	4
//4311200120	5

            #region 通过订单部件明细表[Transfer_Part_Detailed]统计工时
            
            string strSql = "";
            strSql = @"SELECT c.MATERIAL_NO AS 产品,CN_DESC AS 产品描述,QTY AS 数量,
CAST(SUM(COMB_TIME*Part_QTY)/60 AS decimal(18,2)) AS [工时(分)] 
FROM 
(SELECT MATERIAL_NO,b.CN_DESC,QTY 
FROM OP_Capacity_Evaluation_Temp AS a
LEFT JOIN IE_Part_MasterData AS b
ON a.MATERIAL_NO=b.PART_NO) AS c
LEFT JOIN View_OP_Capacity_Evaluation_Product AS d
ON c.MATERIAL_NO=d.Material_No
GROUP BY c.MATERIAL_NO,CN_DESC,QTY";
            setGridData(gridControl1, gridView1, strSql);//订单数据

            getProcessTime_ByPartDetail("View_OP_Capacity_Evaluation_Product");

            #endregion

//4311200010	4
//4311200120	5

            #region 需提前通过ZP10下载BOM到表[Transfer_ZP10_Simplified_BOM]
//            string strSql = "";
//            strSql = @"SELECT MATERIAL_NO AS 产品,b.CN_DESC AS 产品描述,QTY AS 数量 
//                        FROM OP_Capacity_Evaluation_Temp AS a
//                        LEFT JOIN IE_Part_MasterData AS b
//                        ON a.MATERIAL_NO=b.PART_NO";
//            setGridData(gridControl1, gridView1, strSql);//订单数据        

//            strSql = @"SELECT PRODUCT_NO AS 产品,COMPONENT_NO AS 部件,b.CN_DESC AS 部件描述,CAST(QTY AS decimal(18,2)) AS 合计套内数量,
//                        PROCESS_CODE AS 工序代码,PROCESS_NAME AS 工序名称,LABOR_TIME AS 工时
//                        FROM View_OP_Capacity_Evaluation_Product_ZP10 AS a
//                        LEFT JOIN IE_Part_MasterData AS b
//                        ON a.COMPONENT_NO=b.PART_NO";
//            setGridData(gridControl2, gridView2, strSql);//工时数据      

//            strSql = @"SELECT SUB_FACTORY AS 分厂,SUM(LABOR_TIME) AS 工时
//                    FROM View_OP_Capacity_Evaluation_Product_ZP10
//                    GROUP BY SUB_FACTORY";
//            setGridData(gridControl3, gridView3, strSql);//   

//            strSql = @"SELECT WORKSTATION AS 站点,SUM(LABOR_TIME) AS 工时
//                    FROM View_OP_Capacity_Evaluation_Product_ZP10
//                    GROUP BY WORKSTATION";
//            setGridData(gridControl4, gridView4, strSql);//   

//            strSql = @"SELECT PROCESS_CODE AS 工序,PROCESS_NAME AS 名称,CAST(SUM(LABOR_TIME) AS decimal(18,2)) AS 工时
//                    FROM View_OP_Capacity_Evaluation_Product_ZP10
//                    GROUP BY PROCESS_CODE,PROCESS_NAME";
//            setGridData(gridControl5, gridView5, strSql);//   

            #endregion
        }

        //按订单预估
        private void refreshDataToFront_Order()
        {
//645124020409  一组件多部件
//644957005009  组装包装
//651609001409  多层BOM
//651609000000
       
            string strSql = "";
            strSql = @"SELECT MO_NO AS 订单,Material_Desc AS 产品描述,Order_QTY AS 数量,
CAST(SUM(COMB_TIME*Part_QTY)/60 AS decimal(18,2)) AS [工时(分)] 
FROM 
(SELECT a.MO_NO,b.Material_No,b.Material_Desc,b.Order_QTY
FROM OP_Capacity_Evaluation_Temp AS a 
LEFT JOIN Transfer_Package_List AS b 
ON a.MO_NO = b.Package_Mo) AS c
LEFT JOIN View_OP_Capacity_Evaluation_Order AS d
ON c.Material_No=d.Material_No
GROUP BY MO_NO,Material_Desc,Order_QTY";

            setGridData(gridControl1, gridView1, strSql);//订单数据

            getProcessTime_ByPartDetail("View_OP_Capacity_Evaluation_Order");

            #region 因计划工时数据维护模块未开发，所以暂不提供排产天数分析功能
            //            strSql = @"SELECT 分厂,CAST(计划工时 AS decimal(18,0)) AS 计划工时, 
//                    查询工时,CAST(查询工时/计划工时 AS decimal(18,1)) AS 排产天数 
//                    FROM 
//                    (SELECT SUB_FACTORY AS 分厂, 
//                    SUM(WORKING_HOURS*CURRENT_WORKERS) AS 计划工时, 
//                    CAST(SUM(PROCESS_TIME)/3600 AS decimal(18,2)) AS 查询工时 
//                    FROM View_OP_Plan_Process_Time_Distribution 
//                    WHERE Package_Mo IN(
//					SELECT DISTINCT MO_NO FROM OP_Capacity_Evaluation_Temp)
//                    GROUP BY SUB_FACTORY) AS a";
//            setGridData(gridControl3, gridView3, strSql);

//            strSql = @"SELECT 工作站,CAST(计划工时 AS decimal(18,0)) AS 计划工时, 
//                    查询工时,CAST(查询工时/计划工时 AS decimal(18,1)) AS 排产天数 
//                    FROM 
//                    (SELECT WORKSTATION AS 工作站, 
//                    SUM(WORKING_HOURS*CURRENT_WORKERS) AS 计划工时, 
//                    CAST(SUM(PROCESS_TIME)/3600 AS decimal(18,2)) AS 查询工时 
//                    FROM View_OP_Plan_Process_Time_Distribution 
//                    WHERE Package_Mo IN(
//					SELECT DISTINCT MO_NO FROM OP_Capacity_Evaluation_Temp)
//                    GROUP BY WORKSTATION) AS a";
//            setGridData(gridControl4, gridView4, strSql);

//            strSql = @"SELECT 工序,名称,CAST(计划工时 AS decimal(18,0)) AS 计划工时, 
//                    查询工时,CAST(查询工时/计划工时 AS decimal(18,1)) AS 排产天数 
//                    FROM 
//                    (SELECT PROCESS_CODE AS 工序,PROCESS_NAME AS 名称, 
//                    SUM(WORKING_HOURS*CURRENT_WORKERS) AS 计划工时, 
//                    CAST(SUM(PROCESS_TIME)/3600 AS decimal(18,2)) AS 查询工时 
//                    FROM View_OP_Plan_Process_Time_Distribution 
//                    WHERE Package_Mo IN(
//					SELECT DISTINCT MO_NO FROM OP_Capacity_Evaluation_Temp)
//                    GROUP BY PROCESS_CODE,PROCESS_NAME) AS a";
            //            setGridData(gridControl5, gridView5, strSql);

            #endregion
        }

        //通过订单部件明细表[Transfer_Part_Detailed]统计工时
        private void getProcessTime_ByPartDetail(string strTableView)
        {      
            string strSql = "";
            strSql = @"SELECT Package_Mo AS 订单,Part_No AS 组件,Part_Desc AS 组件描述,
CAST(Part_QTY AS decimal(18,2)) AS 套内数量,
PROCESS_CODE AS 工序代码,PROCESS_NAME AS 工序名称,
CAST(COMB_TIME*Part_QTY AS DECIMAL(18, 2)) AS [工时(秒)]
FROM " + strTableView;
            setGridData(gridControl2, gridView2, strSql);//工时数据

            strSql = @"SELECT SUB_FACTORY AS 工作站, 
CAST(SUM(COMB_TIME*Part_QTY)/60 AS decimal(18,2)) AS [工时(分)] 
FROM " + strTableView + @"
GROUP BY SUB_FACTORY";
            setGridData(gridControl3, gridView3, strSql);

            strSql = @"SELECT WORKSTATION AS 工作站, 
CAST(SUM(COMB_TIME*Part_QTY)/60 AS decimal(18,2)) AS [工时(分)] 
FROM " + strTableView + @"
GROUP BY WORKSTATION";
            setGridData(gridControl4, gridView4, strSql);

            strSql = @"SELECT PROCESS_CODE AS 工作中心,PROCESS_NAME AS 工序描述, 
CAST(SUM(COMB_TIME*Part_QTY)/60 AS decimal(18,2)) AS [工时(分)] 
FROM " + strTableView + @"
GROUP BY PROCESS_CODE,PROCESS_NAME";
            setGridData(gridControl5, gridView5, strSql);
        }

        private void setGridData(DevExpress.XtraGrid.GridControl gc,DevExpress.XtraGrid.Views.Grid.GridView gv,string strSql)
        {
            DataTable dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);

            gc.DataSource = dt;
            //setGridViewColumnAutoWidth(gv);
            gv.OptionsBehavior.Editable = false;
            //gv.OptionsView.ColumnAutoWidth = true;
            //gv.Columns[0].BestFit();
            //gv.Columns[1].BestFit();
            //gv.BestFitColumns();
            //setGridViewColumnAutoWidth();

        }

        //gridView仅复制单元格内容，复制选中行焦点单元格的值
        private void gridView5_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control & e.KeyCode == Keys.C)
            {
                Clipboard.SetDataObject(gridView5.GetFocusedRowCellValue(gridView5.FocusedColumn));
                e.Handled = true;
            }

            //或设置属性
            //optionBehavior - CopyToClipboardWithColumnHeader = false;
            //optionSelection - MultiSelectMode = CellSelect;
        }

        private void 导出一ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Lamex.Common.ExecelHelper.GridViewToExcel(gridView2);
        }

        private void 打印一ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Lamex.Common.ExecelHelper.GridViewToPrint(gridControl2, this.Text);
        }

        private void 导出二ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Lamex.Common.ExecelHelper.GridViewToExcel(gridView5);
        }

        private void 打印二ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Lamex.Common.ExecelHelper.GridViewToPrint(gridControl5, this.Text);
        }

        private void 导出三ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Lamex.Common.ExecelHelper.GridViewToExcel(gridView1);
        }

        private void 打印三ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Lamex.Common.ExecelHelper.GridViewToPrint(gridControl1, this.Text);
        }

        //设置说明列
        private void TotalSum_FirstColumn()
        {
            gridView1.Columns[0].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            gridView1.Columns[0].SummaryItem.DisplayFormat = "合计：";

            gridView2.Columns[0].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            gridView2.Columns[0].SummaryItem.DisplayFormat = "合计：";

            gridView3.Columns[0].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            gridView3.Columns[0].SummaryItem.DisplayFormat = "合计：";

            gridView4.Columns[0].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            gridView4.Columns[0].SummaryItem.DisplayFormat = "合计：";

            gridView5.Columns[0].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            gridView5.Columns[0].SummaryItem.DisplayFormat = "合计：";

        }

        //设置其他列汇总
        private void TotalSum_OtherColumn()
        {
            //{0:0.##}

            gridView1.Columns[2].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
            gridView1.Columns[2].SummaryItem.DisplayFormat = "{0:N}";

            gridView2.Columns[3].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
            gridView2.Columns[3].SummaryItem.DisplayFormat = "{0:N}";
            gridView2.Columns[6].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
            gridView2.Columns[6].SummaryItem.DisplayFormat = "{0:N}";

            gridView3.Columns[1].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
            gridView3.Columns[1].SummaryItem.DisplayFormat = "{0:N}";

            gridView4.Columns[1].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
            gridView4.Columns[1].SummaryItem.DisplayFormat = "{0:N}";

            gridView5.Columns[2].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
            gridView5.Columns[2].SummaryItem.DisplayFormat = "{0:N}";
        }

        #region 实例化标准功能

        public override void DoView(IButtonInfo sender)
        {
            sbtnView_Click(null, null);
            base.DoView(sender);
        }

        private void 隐藏选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelControl_Top.Height = 0;
        }

        private void 显示选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelControl_Top.Height = 60;
        }

        #endregion


    }
}